{% extends "base.html" %}

{% block title %}我的会议{% endblock %}

{% block content %}
<div class="container mt-4">
    <h2>我的会议</h2>
    <div class="row mb-3">
        <div class="col-md-6">
            <input type="text" id="searchInput" class="form-control" placeholder="搜索会议...">
        </div>
        <div class="col-md-3">
            <select id="dateFilter" class="form-select">
                <option value="">所有日期</option>
                <option value="today">今天</option>
                <option value="week">本周</option>
                <option value="month">本月</option>
            </select>
        </div>
        <div class="col-md-3">
            <button id="createMeetingBtn" class="btn btn-primary">创建会议</button>
        </div>
    </div>
    <div class="table-responsive">
        <table class="table table-striped">
            <thead>
                <tr>
                    <th>标题</th>
                    <th>会议室</th>
                    <th>开始时间</th>
                    <th>结束时间</th>
                    <th>创建者</th>
                    <th>状态</th>
                    <th>操作</th>
                </tr>
            </thead>
            <tbody id="meetingsTableBody">
                <!-- 会议数据将通过 JavaScript 动态加载 -->
            </tbody>
        </table>
    </div>
    <nav aria-label="Page navigation">
        <ul class="pagination justify-content-center" id="pagination">
            <!-- 分页控件将通过 JavaScript 动态加载 -->
        </ul>
    </nav>
</div>

<script>
    let currentPage = 1;
    const pageSize = 10;
    let userId = null; // 存储当前用户ID

    // 获取当前用户信息
    async function getCurrentUser() {
        try {
            const token = localStorage.getItem('token');
            if (!token) {
                return null;
            }
            
            const response = await axios.get('/api/users/me');
            console.log('当前用户:', response.data);
            return response.data;
        } catch (error) {
            console.error('获取用户信息失败:', error);
            return null;
        }
    }

    async function loadMyMeetings(page = 1, search = '', dateFilter = '') {
        try {
            // 检查token
            const token = localStorage.getItem('token');
            if (!token) {
                console.log('未找到token，无法加载会议');
                showLoginRequired();
                return;
            }
            
            // 确保请求头中包含token
            axios.defaults.headers.common['Authorization'] = 'Bearer ' + token;
            
            console.log('正在获取我的会议列表...');
            
            // 使用正确的API路径
            const response = await axios.get('/api/meetings/my-meetings', {
                params: {
                    skip: (page - 1) * pageSize,
                    limit: pageSize,
                    search: search,
                    date_filter: dateFilter
                }
            });
            
            console.log('获取到会议数据:', response.data);
            
            // 处理返回的会议数据
            const meetings = response.data; // API直接返回会议数组
            renderMeetings(meetings);
            
            // 没有total字段，所以只能使用当前获取的数量
            // 如果返回的会议数等于pageSize，说明可能还有更多
            const hasMore = meetings.length === pageSize;
            renderPagination(hasMore ? (page * pageSize) + 1 : page * pageSize, page);
            
            // 显示获取到的会议数量
            if (meetings.length === 0) {
                const tbody = document.getElementById('meetingsTableBody');
                tbody.innerHTML = `
                    <tr>
                        <td colspan="7" class="text-center py-3">
                            没有找到会议记录
                            <div class="mt-2">
                                <a href="/meetings/create" class="btn btn-sm btn-primary">预约新会议</a>
                            </div>
                        </td>
                    </tr>
                `;
            }
        } catch (error) {
            console.error('获取我的会议失败:', error);
            
            if (error.response && error.response.status === 401) {
                // 认证失败，清除token并显示登录提示
                localStorage.removeItem('token');
                delete axios.defaults.headers.common['Authorization'];
                showLoginRequired();
                return;
            }
            
            // 显示其他错误信息
            const tbody = document.getElementById('meetingsTableBody');
            tbody.innerHTML = `
                <tr>
                    <td colspan="7" class="text-center text-danger py-3">
                        获取会议数据失败: ${error.response?.data?.detail || error.message || '未知错误'}
                        <div class="mt-2">
                            <button class="btn btn-sm btn-outline-primary" onclick="loadMyMeetings()">重试</button>
                        </div>
                    </td>
                </tr>
            `;
        }
    }

    function renderMeetings(meetings) {
        const tbody = document.getElementById('meetingsTableBody');
        tbody.innerHTML = '';
        
        if (!meetings || meetings.length === 0) {
            return; // 早已处理了空数据情况
        }
        // 按开始时间降序排序（越新的越前）
        meetings.sort((a, b) => new Date(b.start_time) - new Date(a.start_time));
        meetings.forEach(meeting => {
            // 处理房间信息 - 兼容多种返回格式
            const roomName = meeting.room_name || (meeting.room ? meeting.room.name : '未知');
            
            // 处理所有者信息
            const ownerName = meeting.owner_name || (meeting.owner ? meeting.owner.username : '未知');
            
            // 检查用户是否为会议所有者
            const isOwner = meeting.is_owner || false;
            
            // 获取会议状态
            let status = '进行中';
            if (meeting.is_cancelled) {
                status = '<span class="badge bg-danger">已取消</span>';
            } else {
                const now = new Date();
                const startTime = new Date(meeting.start_time);
                const endTime = new Date(meeting.end_time);
                
                if (now < startTime) {
                    status = '<span class="badge bg-primary">待开始</span>';
                } else if (now > endTime) {
                    status = '<span class="badge bg-secondary">已结束</span>';
                } else {
                    status = '<span class="badge bg-success">进行中</span>';
                }
            }
            
            const row = document.createElement('tr');
            // 只显示取消按钮（如果有权限且未取消）
            let actionTd = '';
            if (meeting.owner && meeting.owner.id === userId && !meeting.is_cancelled) {
                actionTd = `<button class=\"btn btn-sm btn-danger\" onclick=\"cancelMeeting(${meeting.id})\">取消</button>`;
            }
            row.innerHTML = `
                <td><a href=\"/meetings/${meeting.id}\" class=\"text-decoration-none\">${meeting.title}</a></td>
                <td>${roomName}</td>
                <td>${new Date(meeting.start_time).toLocaleString()}</td>
                <td>${new Date(meeting.end_time).toLocaleString()}</td>
                <td>${ownerName}</td>
                <td>${status}</td>
                <td>${actionTd}</td>
            `;
            tbody.appendChild(row);
        });
    }

    function renderPagination(total, currentPage) {
        const totalPages = Math.ceil(total / pageSize);
        const pagination = document.getElementById('pagination');
        pagination.innerHTML = '';
        
        // Previous button
        pagination.innerHTML += `
            <li class="page-item ${currentPage === 1 ? 'disabled' : ''}">
                <a class="page-link" href="#" data-page="${currentPage - 1}">上一页</a>
            </li>
        `;
        
        // Page numbers
        for (let i = 1; i <= totalPages; i++) {
            pagination.innerHTML += `
                <li class="page-item ${i === currentPage ? 'active' : ''}">
                    <a class="page-link" href="#" data-page="${i}">${i}</a>
                </li>
            `;
        }
        
        // Next button
        pagination.innerHTML += `
            <li class="page-item ${currentPage === totalPages ? 'disabled' : ''}">
                <a class="page-link" href="#" data-page="${currentPage + 1}">下一页</a>
            </li>
        `;
    }

    async function editMeeting(meetingId) {
        window.location.href = `/meetings/${meetingId}/edit`;
    }

    async function cancelMeeting(meetingId) {
        if (confirm('确定要取消这个会议吗？')) {
            try {
                // 确保认证状态
                initAuth();
                
                // 使用正确的API路径
                const response = await axios.post(`/api/meetings/${meetingId}/cancel`);
                
                console.log('取消会议成功:', response.data);
                
                // 请求成功直接刷新数据
                loadMyMeetings(currentPage, document.getElementById('searchInput').value, document.getElementById('dateFilter').value);
            } catch (error) {
                console.error('取消会议失败:', error);
                alert('取消会议失败: ' + (error.response?.data?.detail || '未知错误'));
            }
        }
    }

    // Event listeners
    document.getElementById('searchInput').addEventListener('input', (e) => {
        loadMyMeetings(1, e.target.value, document.getElementById('dateFilter').value);
    });

    document.getElementById('dateFilter').addEventListener('change', (e) => {
        loadMyMeetings(1, document.getElementById('searchInput').value, e.target.value);
    });

    document.getElementById('pagination').addEventListener('click', (e) => {
        e.preventDefault();
        if (e.target.tagName === 'A') {
            const page = parseInt(e.target.dataset.page);
            if (page && page !== currentPage) {
                currentPage = page;
                loadMyMeetings(page, document.getElementById('searchInput').value, document.getElementById('dateFilter').value);
            }
        }
    });

    document.getElementById('createMeetingBtn').addEventListener('click', () => {
        window.location.href = '/meetings/create';
    });

    // 显示需要登录的提示
    function showLoginRequired() {
        const tbody = document.getElementById('meetingsTableBody');
        tbody.innerHTML = `
            <tr>
                <td colspan="7" class="text-center text-danger py-3">
                    未登录或登录已过期，请先登录
                    <div class="mt-2">
                        <a href="/login" class="btn btn-primary">去登录</a>
                    </div>
                </td>
            </tr>
        `;
    }

    // 页面加载时确保认证
    document.addEventListener('DOMContentLoaded', async function() {
        console.log('页面加载完成，开始检查认证状态');
        
        // 检查是否有token
        const token = localStorage.getItem('token');
        if (!token) {
            console.log('未找到token，显示登录提示');
            showLoginRequired();
            return;
        }
        
        // 确保请求头中包含token
        axios.defaults.headers.common['Authorization'] = 'Bearer ' + token;
        
        try {
            // 验证token并获取用户信息
            const response = await axios.get('/api/users/me');
            userId = response.data.id;
            console.log('获取到用户ID:', userId);
            
            // 加载会议列表
            loadMyMeetings();
        } catch (error) {
            console.error('验证token失败:', error);
            if (error.response && error.response.status === 401) {
                // token无效，清除
                localStorage.removeItem('token');
                delete axios.defaults.headers.common['Authorization'];
            }
            showLoginRequired();
        }
    });
</script>
{% endblock %} 